/**
 * @file transport_net.c
 * @brief 网络传输驱动实现
 * @details 本文件实现了通用的网络传输驱动，提供基于TCP/UDP协议的网络传输功能。
 *          不包含任何协议特定逻辑，只负责底层网络通信。
 * 
 * @author 电网协议开发团队
 * @date 2024
 * @version 1.0
 */

#define _POSIX_C_SOURCE 200809L  // 确保usleep可用

#include "../include/transport_net.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>  // nanosleep需要

/* ==================== 网络传输私有数据结构 ==================== */

/**
 * @brief 网络传输私有数据
 */
typedef struct {
    int socket_fd;                          /* Socket文件描述符 */
    struct sockaddr_in server_addr;         /* 服务器地址 */
    net_transport_config_t config;          /* 网络配置 */
    net_transport_status_t status;          /* 传输状态 */
    net_transport_stats_t stats;            /* 统计信息 */
    
    /* 回调函数 */
    net_transport_receive_callback_t receive_callback;
    void* receive_user_data;
    net_transport_status_callback_t status_callback;
    void* status_user_data;
    net_transport_error_callback_t error_callback;
    void* error_user_data;
    
    /* 线程相关 */
    pthread_t receive_thread;               /* 接收线程 */
    pthread_t heartbeat_thread;             /* 心跳检测线程 */
    bool thread_running;                    /* 线程运行标志 */
    bool heartbeat_running;                 /* 心跳线程运行标志 */
    pthread_mutex_t mutex;                  /* 互斥锁 */
    
    /* 缓冲区 */
    uint8_t receive_buffer[4096];           /* 接收缓冲区 */
    size_t buffer_size;                     /* 缓冲区大小 */
    size_t buffer_offset;                   /* 缓冲区偏移 */
    
    /* 心跳相关 */
    struct timeval last_activity_time;      /* 最后一次活动时间（发送或接收数据） */
    struct timeval last_heartbeat_time;     /* 最后一次心跳时间 */
    bool heartbeat_response_received;       /* 心跳响应是否收到 */
} transport_net_private_t;

/* ==================== 全局变量 ==================== */

static bool g_net_initialized = false;

/* ==================== 内部函数声明 ==================== */

static void* transport_net_receive_thread(void* arg);
static void* transport_net_heartbeat_thread(void* arg);
static void update_activity_time(transport_net_private_t* private_data);

/* ==================== 全局函数实现 ==================== */

/**
 * @brief 初始化网络传输驱动
 */
net_transport_error_t transport_net_init(void) {
    if (g_net_initialized) {
        return NET_TRANSPORT_ERROR_ALREADY_CONNECTED;
    }
    
    g_net_initialized = true;
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 清理网络传输驱动
 */
net_transport_error_t transport_net_cleanup(void) {
    if (!g_net_initialized) {
        return NET_TRANSPORT_ERROR_INIT_FAILED;
    }
    
    g_net_initialized = false;
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 创建网络传输实例
 */
void* transport_net_create(const net_transport_config_t* config) {
    if (config == NULL) {
        return NULL;
    }
    
    if (!g_net_initialized) {
        return NULL;
    }
    
    // 分配内存
    transport_net_private_t* private_data = malloc(sizeof(transport_net_private_t));
    if (private_data == NULL) {
        return NULL;
    }
    
    // 初始化私有数据结构
    memset(private_data, 0, sizeof(transport_net_private_t));
    
    // 复制配置
    memcpy(&private_data->config, config, sizeof(net_transport_config_t));
    
    // 初始化状态
    private_data->status = NET_TRANSPORT_STATUS_DISCONNECTED;
    private_data->socket_fd = -1;
    
    // 初始化互斥锁
    if (pthread_mutex_init(&private_data->mutex, NULL) != 0) {
        free(private_data);
        return NULL;
    }
    
    // 设置Socket为非阻塞模式
    private_data->socket_fd = socket(AF_INET, 
                                    SOCK_STREAM,
                                   0);
    if (private_data->socket_fd < 0) {
        pthread_mutex_destroy(&private_data->mutex);
        free(private_data);
        return NULL;
    }
    
    // 设置Socket选项
    int flags = fcntl(private_data->socket_fd, F_GETFL, 0);
    if (flags < 0) {
        close(private_data->socket_fd);
        pthread_mutex_destroy(&private_data->mutex);
        free(private_data);
        return NULL;
    }
    
    if (fcntl(private_data->socket_fd, F_SETFL, flags | O_NONBLOCK) < 0) {
        close(private_data->socket_fd);
        pthread_mutex_destroy(&private_data->mutex);
        free(private_data);
        return NULL;
    }
    
    // 配置服务器地址
    memset(&private_data->server_addr, 0, sizeof(struct sockaddr_in));
    private_data->server_addr.sin_family = AF_INET;
    private_data->server_addr.sin_port = htons(private_data->config.server_port);
    
    if (inet_pton(AF_INET, private_data->config.server_ip, &private_data->server_addr.sin_addr) <= 0) {
        close(private_data->socket_fd);
        pthread_mutex_destroy(&private_data->mutex);
        free(private_data);
        return NULL;
    }
    
    return private_data;
}

/**
 * @brief 销毁网络传输实例
 */
net_transport_error_t transport_net_destroy(void* instance) {
    if (instance == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    // 停止心跳线程
    if (private_data->heartbeat_running) {
        private_data->heartbeat_running = false;
        pthread_join(private_data->heartbeat_thread, NULL);
    }
    
    // 停止接收线程
    if (private_data->thread_running) {
        private_data->thread_running = false;
        pthread_join(private_data->receive_thread, NULL);
    }
    
    // 关闭Socket
    if (private_data->socket_fd >= 0) {
        close(private_data->socket_fd);
        private_data->socket_fd = -1;
    }
    
    // 销毁互斥锁
    pthread_mutex_destroy(&private_data->mutex);
    
    // 释放内存
    free(private_data);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 连接网络传输
 */
net_transport_error_t transport_net_connect(void* instance) {
    if (instance == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    
    if (private_data->status == NET_TRANSPORT_STATUS_CONNECTED) {
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_ERROR_ALREADY_CONNECTED;
    }
    
    if (private_data->status == NET_TRANSPORT_STATUS_CONNECTING) {
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_ERROR_ALREADY_CONNECTED;
    }
    
    private_data->status = NET_TRANSPORT_STATUS_CONNECTING;
    
    // 尝试连接
    int result = connect(private_data->socket_fd, 
                        (struct sockaddr*)&private_data->server_addr, 
                        sizeof(private_data->server_addr));
    
    if (result < 0) {
        if (errno == EINPROGRESS) {
            // 连接正在进行中，需要等待
            fd_set write_fds;
            struct timeval timeout;
            
            FD_ZERO(&write_fds);
            FD_SET(private_data->socket_fd, &write_fds);
            
            timeout.tv_sec = private_data->config.timeout_ms / 1000;
            timeout.tv_usec = (private_data->config.timeout_ms % 1000) * 1000;
            
            result = select(private_data->socket_fd + 1, NULL, &write_fds, NULL, &timeout);
            
            if (result > 0) {
                // 检查连接是否成功
                int error = 0;
                socklen_t len = sizeof(error);
                if (getsockopt(private_data->socket_fd, SOL_SOCKET, SO_ERROR, &error, &len) == 0) {
                    if (error == 0) {
                        private_data->status = NET_TRANSPORT_STATUS_CONNECTED;
                        
                        // 初始化活动时间
                        gettimeofday(&private_data->last_activity_time, NULL);
                        gettimeofday(&private_data->last_heartbeat_time, NULL);
                        private_data->heartbeat_response_received = true;
                        
                        // 启动接收线程
                        private_data->thread_running = true;
                        if (pthread_create(&private_data->receive_thread, NULL, transport_net_receive_thread, private_data) != 0) {
                            private_data->thread_running = false;
                            private_data->status = NET_TRANSPORT_STATUS_ERROR;
                            pthread_mutex_unlock(&private_data->mutex);
                            return NET_TRANSPORT_ERROR_SYSTEM;
                        }
                        
                        // 启动心跳线程（如果启用）
                        if (private_data->config.heartbeat_interval > 0) {
                            private_data->heartbeat_running = true;
                            if (pthread_create(&private_data->heartbeat_thread, NULL, transport_net_heartbeat_thread, private_data) != 0) {
                                private_data->heartbeat_running = false;
                                // 心跳线程启动失败不影响连接，只记录错误
                            }
                        }
                        
                        // 调用状态回调
                        if (private_data->status_callback) {
                            private_data->status_callback(NET_TRANSPORT_STATUS_CONNECTED, private_data->status_user_data);
                        }
                        
                        pthread_mutex_unlock(&private_data->mutex);
                        return NET_TRANSPORT_SUCCESS;
                    } else {
                        private_data->status = NET_TRANSPORT_STATUS_ERROR;
                        pthread_mutex_unlock(&private_data->mutex);
                        return NET_TRANSPORT_ERROR_CONNECT_FAILED;
                    }
                } else {
                    private_data->status = NET_TRANSPORT_STATUS_ERROR;
                    
                    // 连接失败，调用错误回调（报警）
                    if (private_data->error_callback) {
                        private_data->error_callback(NET_TRANSPORT_ERROR_CONNECT_FAILED, private_data->error_user_data);
                    }
                    
                    pthread_mutex_unlock(&private_data->mutex);
                    return NET_TRANSPORT_ERROR_CONNECT_FAILED;
                }
            } else {
                private_data->status = NET_TRANSPORT_STATUS_ERROR;
                
                // 连接超时，调用错误回调（报警）
                if (private_data->error_callback) {
                    private_data->error_callback(NET_TRANSPORT_ERROR_TIMEOUT, private_data->error_user_data);
                }
                
                pthread_mutex_unlock(&private_data->mutex);
                return NET_TRANSPORT_ERROR_TIMEOUT;
            }
        } else {
            private_data->status = NET_TRANSPORT_STATUS_ERROR;
            pthread_mutex_unlock(&private_data->mutex);
            return NET_TRANSPORT_ERROR_CONNECT_FAILED;
        }
    } else {
        // 连接立即成功
        private_data->status = NET_TRANSPORT_STATUS_CONNECTED;
        
        // 初始化活动时间
        gettimeofday(&private_data->last_activity_time, NULL);
        gettimeofday(&private_data->last_heartbeat_time, NULL);
        private_data->heartbeat_response_received = true;
        
        // 启动接收线程
        private_data->thread_running = true;
        if (pthread_create(&private_data->receive_thread, NULL, transport_net_receive_thread, private_data) != 0) {
            private_data->thread_running = false;
            private_data->status = NET_TRANSPORT_STATUS_ERROR;
            pthread_mutex_unlock(&private_data->mutex);
            return NET_TRANSPORT_ERROR_SYSTEM;
        }
        
        // 启动心跳线程（如果启用）
        if (private_data->config.heartbeat_interval > 0) {
            private_data->heartbeat_running = true;
            if (pthread_create(&private_data->heartbeat_thread, NULL, transport_net_heartbeat_thread, private_data) != 0) {
                private_data->heartbeat_running = false;
                // 心跳线程启动失败不影响连接，只记录错误
            }
        }
        
        // 调用状态回调
        if (private_data->status_callback) {
            private_data->status_callback(NET_TRANSPORT_STATUS_CONNECTED, private_data->status_user_data);
        }
        
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_SUCCESS;
    }
}

/**
 * @brief 断开网络传输
 */
net_transport_error_t transport_net_disconnect(void* instance) {
    if (instance == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    
    if (private_data->status == NET_TRANSPORT_STATUS_DISCONNECTED) {
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_ERROR_NOT_CONNECTED;
    }
    
    private_data->status = NET_TRANSPORT_STATUS_DISCONNECTING;
    
    // 停止接收线程
    if (private_data->thread_running) {
        private_data->thread_running = false;
        pthread_mutex_unlock(&private_data->mutex);
        pthread_join(private_data->receive_thread, NULL);
        pthread_mutex_lock(&private_data->mutex);
    }
    
    // 关闭Socket
    if (private_data->socket_fd >= 0) {
        close(private_data->socket_fd);
        private_data->socket_fd = -1;
    }
    
    private_data->status = NET_TRANSPORT_STATUS_DISCONNECTED;
    
    // 调用状态回调
    if (private_data->status_callback) {
        private_data->status_callback(NET_TRANSPORT_STATUS_DISCONNECTED, private_data->status_user_data);
    }
    
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 获取网络传输状态
 */
net_transport_status_t transport_net_get_status(void* instance) {
    if (instance == NULL) {
        return NET_TRANSPORT_STATUS_ERROR;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    net_transport_status_t status = private_data->status;
    pthread_mutex_unlock(&private_data->mutex);
    
    return status;
}

/**
 * @brief 网络传输发送数据
 */
net_transport_error_t transport_net_send(void* instance, const uint8_t* data, size_t length) {
    if (instance == NULL || data == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    if (length == 0) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    
    if (private_data->status != NET_TRANSPORT_STATUS_CONNECTED) {
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_ERROR_NOT_CONNECTED;
    }
    
    ssize_t bytes_sent;
    
    if (true) {
        // TCP发送
        bytes_sent = send(private_data->socket_fd, data, length, 0);
    } else {
        // UDP发送
        bytes_sent = sendto(private_data->socket_fd, data, length, 0,
                           (struct sockaddr*)&private_data->server_addr,
                           sizeof(private_data->server_addr));
    }
    
    if (bytes_sent < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            // 发送缓冲区满，等待可写
            fd_set write_fds;
            struct timeval timeout;
            
            FD_ZERO(&write_fds);
            FD_SET(private_data->socket_fd, &write_fds);
            
            timeout.tv_sec = private_data->config.timeout_ms / 1000;
            timeout.tv_usec = (private_data->config.timeout_ms % 1000) * 1000;
            
            int result = select(private_data->socket_fd + 1, NULL, &write_fds, NULL, &timeout);
            
            if (result > 0) {
                if (true) {
                    bytes_sent = send(private_data->socket_fd, data, length, 0);
                } else {
                    bytes_sent = sendto(private_data->socket_fd, data, length, 0,
                                       (struct sockaddr*)&private_data->server_addr,
                                       sizeof(private_data->server_addr));
                }
                
                if (bytes_sent < 0) {
                    private_data->stats.errors++;
                    pthread_mutex_unlock(&private_data->mutex);
                    return NET_TRANSPORT_ERROR_SEND_FAILED;
                }
            } else {
                private_data->stats.timeouts++;
                
                // 发送超时，调用错误回调（报警）
                if (private_data->error_callback) {
                    private_data->error_callback(NET_TRANSPORT_ERROR_TIMEOUT, private_data->error_user_data);
                }
                
                pthread_mutex_unlock(&private_data->mutex);
                return NET_TRANSPORT_ERROR_TIMEOUT;
            }
        } else {
            private_data->stats.errors++;
            pthread_mutex_unlock(&private_data->mutex);
            return NET_TRANSPORT_ERROR_SEND_FAILED;
        }
    }
    
    // 更新统计信息
    private_data->stats.bytes_sent += bytes_sent;
    private_data->stats.packets_sent++;
    
    // 更新活动时间
    update_activity_time(private_data);
    
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 网络传输接收数据
 */
net_transport_error_t transport_net_receive(void* instance, uint8_t* buffer, size_t max_length, size_t* actual_length) {
    if (instance == NULL || buffer == NULL || actual_length == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    if (max_length == 0) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    
    if (private_data->status != NET_TRANSPORT_STATUS_CONNECTED) {
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_ERROR_NOT_CONNECTED;
    }
    
    // 检查缓冲区是否有数据
    if (private_data->buffer_offset > 0) {
        size_t copy_length = (private_data->buffer_offset < max_length) ? 
                            private_data->buffer_offset : max_length;
        
        memcpy(buffer, private_data->receive_buffer, copy_length);
        
        // 移动剩余数据
        if (private_data->buffer_offset > copy_length) {
            memmove(private_data->receive_buffer, 
                   private_data->receive_buffer + copy_length,
                   private_data->buffer_offset - copy_length);
        }
        
        private_data->buffer_offset -= copy_length;
        *actual_length = copy_length;
        
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_SUCCESS;
    }
    
    // 缓冲区为空，尝试接收新数据
    ssize_t bytes_received;
    
    if (true) {
        // TCP接收
        bytes_received = recv(private_data->socket_fd, buffer, max_length, 0);
    } else {
        // UDP接收
        struct sockaddr_in from_addr;
        socklen_t from_len = sizeof(from_addr);
        bytes_received = recvfrom(private_data->socket_fd, buffer, max_length, 0,
                                 (struct sockaddr*)&from_addr, &from_len);
    }
    
    if (bytes_received < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            *actual_length = 0;
            pthread_mutex_unlock(&private_data->mutex);
            return NET_TRANSPORT_ERROR_RECEIVE_FAILED;
        } else {
            private_data->stats.errors++;
            pthread_mutex_unlock(&private_data->mutex);
            return NET_TRANSPORT_ERROR_RECEIVE_FAILED;
        }
    } else if (bytes_received == 0) {
        // 连接被对端关闭
        private_data->status = NET_TRANSPORT_STATUS_DISCONNECTED;
        
        // 连接断开，调用错误回调（报警）
        if (private_data->error_callback) {
            private_data->error_callback(NET_TRANSPORT_ERROR_NOT_CONNECTED, private_data->error_user_data);
        }
        
        // 调用状态回调
        if (private_data->status_callback) {
            private_data->status_callback(NET_TRANSPORT_STATUS_DISCONNECTED, private_data->status_user_data);
        }
        
        pthread_mutex_unlock(&private_data->mutex);
        return NET_TRANSPORT_ERROR_NOT_CONNECTED;
    }
    
    // 更新统计信息
    private_data->stats.bytes_received += bytes_received;
    private_data->stats.packets_received++;
    *actual_length = bytes_received;
    
    // 更新活动时间
    update_activity_time(private_data);
    private_data->heartbeat_response_received = true;
    
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 设置网络传输接收回调
 */
net_transport_error_t transport_net_set_receive_callback(void* instance, net_transport_receive_callback_t callback, void* user_data) {
    if (instance == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    private_data->receive_callback = callback;
    private_data->receive_user_data = user_data;
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 设置网络传输状态回调
 */
net_transport_error_t transport_net_set_status_callback(void* instance, net_transport_status_callback_t callback, void* user_data) {
    if (instance == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    private_data->status_callback = callback;
    private_data->status_user_data = user_data;
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 设置网络传输错误回调
 */
net_transport_error_t transport_net_set_error_callback(void* instance, net_transport_error_callback_t callback, void* user_data) {
    if (instance == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    private_data->error_callback = callback;
    private_data->error_user_data = user_data;
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 获取网络传输统计信息
 */
net_transport_error_t transport_net_get_stats(void* instance, net_transport_stats_t* stats) {
    if (instance == NULL || stats == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    memcpy(stats, &private_data->stats, sizeof(net_transport_stats_t));
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/**
 * @brief 重置网络传输统计信息
 */
net_transport_error_t transport_net_reset_stats(void* instance) {
    if (instance == NULL) {
        return NET_TRANSPORT_ERROR_INVALID_PARAM;
    }
    
    transport_net_private_t* private_data = (transport_net_private_t*)instance;
    
    pthread_mutex_lock(&private_data->mutex);
    memset(&private_data->stats, 0, sizeof(net_transport_stats_t));
    pthread_mutex_unlock(&private_data->mutex);
    
    return NET_TRANSPORT_SUCCESS;
}

/* ==================== 内部函数实现 ==================== */

/**
 * @brief 网络传输接收线程
 */
static void* transport_net_receive_thread(void* arg) {
    transport_net_private_t* private_data = (transport_net_private_t*)arg;
    
    while (private_data->thread_running) {
        uint8_t buffer[4096];
        size_t actual_length;
        
        net_transport_error_t result = transport_net_receive(private_data, buffer, sizeof(buffer), &actual_length);
        
        if (result == NET_TRANSPORT_SUCCESS && actual_length > 0) {
            // 调用接收回调
            if (private_data->receive_callback) {
                private_data->receive_callback(buffer, actual_length, private_data->receive_user_data);
            }
        } else if (result == NET_TRANSPORT_ERROR_NOT_CONNECTED) {
            // 连接断开，退出线程
            // 状态回调和错误回调已在transport_net_receive中调用
            break;
        }
        
        // 短暂休眠，避免CPU占用过高
        {
            struct timespec ts;
            ts.tv_sec = 0;
            ts.tv_nsec = 1000000L; // 1ms = 1,000,000 纳秒
            nanosleep(&ts, NULL);
        }
    }
    
    return NULL;
}

/**
 * @brief 更新活动时间
 */
static void update_activity_time(transport_net_private_t* private_data) {
    if (private_data == NULL) {
        return;
    }
    gettimeofday(&private_data->last_activity_time, NULL);
}

/**
 * @brief 心跳检测线程
 * @details 定期检测连接状态，如果长时间无响应则认为连接断开并报警
 */
static void* transport_net_heartbeat_thread(void* arg) {
    transport_net_private_t* private_data = (transport_net_private_t*)arg;
    
    while (private_data->heartbeat_running && private_data->thread_running) {
        struct timeval current_time;
        gettimeofday(&current_time, NULL);
        
        pthread_mutex_lock(&private_data->mutex);
        
        if (private_data->status != NET_TRANSPORT_STATUS_CONNECTED) {
            pthread_mutex_unlock(&private_data->mutex);
            break;
        }
        
        // 检查是否需要发送心跳（TCP keepalive）
        if (private_data->config.keep_alive) {
            // 计算自上次活动以来的时间（毫秒）
            long elapsed_ms = (current_time.tv_sec - private_data->last_activity_time.tv_sec) * 1000 +
                             (current_time.tv_usec - private_data->last_activity_time.tv_usec) / 1000;
            
            // 如果超过心跳间隔，发送TCP keepalive探测
            if (elapsed_ms >= (long)private_data->config.heartbeat_interval) {
                // 使用TCP keepalive机制检测连接
                int optval = 1;
                setsockopt(private_data->socket_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));
                
                // 检查心跳响应
                uint32_t heartbeat_timeout = private_data->config.heartbeat_timeout > 0 ? 
                                            private_data->config.heartbeat_timeout : 
                                            private_data->config.heartbeat_interval * 2;
                
                long heartbeat_elapsed_ms = (current_time.tv_sec - private_data->last_heartbeat_time.tv_sec) * 1000 +
                                           (current_time.tv_usec - private_data->last_heartbeat_time.tv_usec) / 1000;
                
                // 如果超过心跳超时时间且没有收到响应，认为连接断开
                if (heartbeat_elapsed_ms >= (long)heartbeat_timeout && !private_data->heartbeat_response_received) {
                    private_data->status = NET_TRANSPORT_STATUS_DISCONNECTED;
                    
                    // 连接断开，调用错误回调（报警）
                    if (private_data->error_callback) {
                        private_data->error_callback(NET_TRANSPORT_ERROR_TIMEOUT, private_data->error_user_data);
                    }
                    
                    // 调用状态回调
                    if (private_data->status_callback) {
                        private_data->status_callback(NET_TRANSPORT_STATUS_DISCONNECTED, private_data->status_user_data);
                    }
                    
                    pthread_mutex_unlock(&private_data->mutex);
                    break;
                }
                
                // 更新心跳时间
                if (private_data->heartbeat_response_received) {
                    gettimeofday(&private_data->last_heartbeat_time, NULL);
                    private_data->heartbeat_response_received = false;
                }
            }
        }
        
        pthread_mutex_unlock(&private_data->mutex);
        
        // 短暂休眠，避免CPU占用过高
        struct timespec ts;
        ts.tv_sec = 0;
        ts.tv_nsec = 100000000L; // 100ms
        nanosleep(&ts, NULL);
    }
    
    return NULL;
}

/**
 * @brief 获取网络传输错误字符串
 */
const char* transport_net_get_error_string(net_transport_error_t error) {
    switch (error) {
        case NET_TRANSPORT_SUCCESS:
            return "Success";
        case NET_TRANSPORT_ERROR_INVALID_PARAM:
            return "Invalid parameter";
        case NET_TRANSPORT_ERROR_INIT_FAILED:
            return "Initialization failed";
        case NET_TRANSPORT_ERROR_CREATE_FAILED:
            return "Create failed";
        case NET_TRANSPORT_ERROR_CONNECT_FAILED:
            return "Connect failed";
        case NET_TRANSPORT_ERROR_DISCONNECT_FAILED:
            return "Disconnect failed";
        case NET_TRANSPORT_ERROR_SEND_FAILED:
            return "Send failed";
        case NET_TRANSPORT_ERROR_RECEIVE_FAILED:
            return "Receive failed";
        case NET_TRANSPORT_ERROR_TIMEOUT:
            return "Timeout";
        case NET_TRANSPORT_ERROR_NOT_CONNECTED:
            return "Not connected";
        case NET_TRANSPORT_ERROR_ALREADY_CONNECTED:
            return "Already connected";
        case NET_TRANSPORT_ERROR_MEMORY:
            return "Memory error";
        case NET_TRANSPORT_ERROR_SYSTEM:
            return "System error";
        case NET_TRANSPORT_ERROR_UNKNOWN:
        default:
            return "Unknown error";
    }
}
